package com.five.filesync;

import android.os.AsyncTask;

import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class BaseRequest extends AsyncTask<String, Void, Boolean> {

    protected String url;
    protected OnNetCallback callback;
    private Object extra;

    public BaseRequest(String url, OnNetCallback callback) {
        this.url = url;
        this.callback = callback;
    }

    public void setExtra(Object extra) {
        this.extra = extra;
    }

    protected class HttpResult {
        public Response response;
        public String responseString;
        private Object bean;
        public boolean isOk() {
            return response != null && response.isSuccessful();
        }

        public Object getBean() {
            return isOk() ? bean : null;
        }
    }
    protected HttpResult doGetRequest(Class classOfBean) {
        OkHttpClient client = new OkHttpClient();

        // 创建请求
        Request request = new Request.Builder()
                .url(url)
                .build();

        HttpResult result = new HttpResult();
        try {
            result.response = client.newCall(request).execute();
            if (result.isOk()) {
                result.responseString = result.response.body().string();
                result.bean = new Gson().fromJson(result.responseString, classOfBean);
            }
            return result;
        } catch (Exception e) {}
        return result;
    }

    @Override
    protected Boolean doInBackground(String... strings) {
        return null;
    }

    protected void onPostExecute(Boolean ret) {
        if (this.callback != null) {
            this.callback.onResult(ret, extra);
        }
    }
}
